<template>
  <div class="knowledge-base">
    <div class="header">
      <div class="search-container">
        <input type="text" placeholder="输入关键词搜索" v-model="searchQuery" class="search-input">
        <button class="search-button"><el-icon><Search /></el-icon></button>
      </div>
      <button class="new-file-button" @click="showUploadModal = true">新建文件</button>
    </div>
    
    <div v-if="showUploadModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="showUploadModal = false">&times;</span>
        <h2>上传文件</h2>
        <input type="file" @change="handleFileUpload" />
        <button @click="uploadFile">上传</button>
      </div>
    </div>

    <div class="table-container">
      <table class="knowledge-table">
        <thead>
          <tr>
            <th class="column-title">id <el-icon><Sort /></el-icon></th>
            <th class="column-type">知识库id <el-icon><Sort /></el-icon></th>
            <th class="column-source">fileName <el-icon><Sort /></el-icon></th>
            <th class="column-segment">fileType <el-icon><Sort /></el-icon></th>
            <!-- <th class="column-learning">学习状态 <el-icon><Sort /></el-icon></th> -->
            <th class="column-status">创建人 <el-icon><Sort /></el-icon></th>
            <th class="column-permission">创建时间 <el-icon><Sort /></el-icon></th>
            <th class="column-update">更新人 <el-icon><Sort /></el-icon></th>
            <th class="column-create">更新时间 <el-icon><Sort /></el-icon></th>
            <th class="column-operation">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in displayedItems" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.knowledgeBaseId }}</td>
            <td>{{ item.fileName }}</td>
            <td>{{ item.fileType }}</td>
            <!-- <td>
              <div class="status-container">
                <span>{{ item.learningStatus }}</span>
                <el-switch v-model="item.learningEnabled" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
              </div>
            </td> -->
            <td>{{ item.createBy }}</td>
            <td>{{ item.createTime }}</td>
            <td>{{ item.updateBy }}</td>
            <td>{{ item.updateTime }}</td>
            <td class="operation-buttons">
              <button class="operation-button relearn-button" @click="relearn(item.id)">重新学习</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <div class="pagination">
      <div class="pagination-info">共 {{ totalItems }} 条</div>
      <div class="pagination-selector">
        <select v-model="itemsPerPage" @change="updateItemsPerPage">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
        </select>
      </div>
      <div class="pagination-controls">
        <button @click="goToFirstPage" :disabled="currentPage === 1" class="pagination-button">首页</button>
        <button @click="prevPage" :disabled="currentPage === 1" class="pagination-button">
          <el-icon><ArrowLeft /></el-icon>
        </button>
        <span class="page-indicator">{{ currentPage }}</span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-button">
          <el-icon><ArrowRight /></el-icon>
        </button>
        <button @click="goToLastPage" :disabled="currentPage === totalPages" class="pagination-button">尾页</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { Search, Sort, ArrowLeft, ArrowRight } from '@element-plus/icons-vue';

export default {
  name: 'KnowledgeBase',
  components: {
    Search,
    Sort,
    ArrowLeft,
    ArrowRight
  },
  methods: {
    async fetchRecords() {
      try {
        const response = await axios.get('api/knowlegeList');
        this.records = response.data.records;
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    }
  },
  setup() {
    const items = ref([]);
    const searchQuery = ref('');
    const currentPage = ref(1);
    const itemsPerPage = ref(10);
    const totalItems = ref(0);
    const showUploadModal = ref(false);
    const selectedFile = ref(null);

    

    // 过滤和分页后的数据
    const filteredItems = computed(() => {
      if (!searchQuery.value) {
        return items.value;
      }
      return items.value.filter(item => 
        item.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        item.type.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        item.source.toLowerCase().includes(searchQuery.value.toLowerCase())
      );
    });

    const displayedItems = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage.value;
      const end = start + itemsPerPage.value;
      return filteredItems.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredItems.value.length / itemsPerPage.value);
    });

    // 获取数据
    const fetchData = async () => {
      try {
        const response = await axios.get('api/knowlegeList');
        const mockData = response.data.records;

        items.value = mockData;
        totalItems.value = mockData.length;
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    // 文件上传处理
    const handleFileUpload = (event) => {
      selectedFile.value = event.target.files[0];
    };

    // 重新学习
    const relearn = async(id) => {
      console.info(id);
      try {
        const response = await axios.get(`api/relearn?docId=${id}`);
         alert("学习完成");
      } catch (error) {
        console.error('重新学习:', error);
      }
    
    };

    const uploadFile = async () => {
      if (!selectedFile.value) {
        alert("请先选择一个文件");
        return;
      }

      const formData = new FormData();
      formData.append("file", selectedFile.value);

      try {
        const response = await axios.post("api/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        console.log("文件上传成功:", response.data);
        showUploadModal.value = false; // Close modal after upload
        fetchData();
      } catch (error) {
        console.error("文件上传失败:", error);
      }
    };

    // 分页方法
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };

    const goToFirstPage = () => {
      currentPage.value = 1;
    };

    const goToLastPage = () => {
      currentPage.value = totalPages.value;
    };

    const updateItemsPerPage = () => {
      currentPage.value = 1; // 重置到第一页
    };

    // 组件挂载时获取数据
    onMounted(() => {
      fetchData();
    });

    return {
      items,
      searchQuery,
      currentPage,
      itemsPerPage,
      totalItems,
      displayedItems,
      totalPages,
      prevPage,
      nextPage,
      goToFirstPage,
      goToLastPage,
      updateItemsPerPage,
      showUploadModal,
      handleFileUpload,
      relearn,
      uploadFile
    };
  }
};
</script>

<style scoped>
.knowledge-base {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 4px;
  padding: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-input {
  border: none;
  outline: none;
  padding: 8px;
  width: 200px;
  font-size: 14px;
}

.search-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
}

.new-file-button {
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 20px;
  height: 36px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
}

.table-container {
  flex: 1;
  overflow-x: auto;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.knowledge-table {
  width: 100%;
  border-collapse: collapse;
}

.knowledge-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  text-align: left;
  padding: 12px 8px;
  border-bottom: 1px solid #EBEEF5;
}

.knowledge-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #EBEEF5;
  color: #606266;
}

.status-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.operation-button {
  padding: 6px 10px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: white;
  color: #606266;
  cursor: pointer;
  font-size: 12px;
}

.info-button {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.edit-button {
  color: #67C23A;
  border-color: #c2e7b0;
  background-color: #f0f9eb;
}

.relearn-button {
  color: #E6A23C;
  border-color: #f5dab1;
  background-color: #fdf6ec;
}

.more-button {
  color: #909399;
  border-color: #d3d4d6;
  background-color: #f4f4f5;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination-selector select {
  padding: 5px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: white;
  color: #606266;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-button {
  padding: 6px 10px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: white;
  color: #606266;
  cursor: pointer;
}

.pagination-button:disabled {
  color: #C0C4CC;
  cursor: not-allowed;
}

.page-indicator {
  padding: 6px 10px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: #409EFF;
  color: white;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .column-permission, .column-update {
    display: none;
  }
}

@media (max-width: 992px) {
  .column-source, .column-segment {
    display: none;
  }
  
  .operation-buttons {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-container {
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
  
  .new-file-button {
    width: 100%;
  }
}
</style>
